<?php

class UtilsHelper
{
    // 全局过滤敏感词
    public static function filter_sensitive_word($post)
    {
        foreach ($post as $k => $v) {
            $post[$k] = self::replace_sensitive_word($v);
        }
        return $post;
    }
    
    // 替换指定的敏感词
    public static function replace_sensitive_word($word)
    {
        $arr = file("./sensitive_word.txt"); // 敏感词典
        $arr1 = array();
        foreach ($arr as $k => $v) {
            $arr1["num" . $k] = trim($v);
        }
        return $content = str_replace($arr1, "*", $word);
    }

    public static function getPositionStr($position)
    {
        $positionStr = "";
        switch ($position) {
            case Lawyer::POSITION_JUNIOR:
                $positionStr = "初级律师";
                break;
            case Lawyer::POSITION_SENIOR:
                $positionStr = "高级律师";
                break;
            case Lawyer::POSITION_PARTNER:
                $positionStr = "合伙人";
                break;
        }
        return $positionStr;
    }

    public static function documentCats()
    {
        $type_instrument_list = Article::getArticleClassList(null, 'type_instrument');
        $case_cats = [];
        foreach($type_instrument_list as $id => $name) {
            $case_cats[] = ['key' => $id, 'value' => $name];
        }
        return $case_cats;
    } 

    public static function workScopeKeyValue()
    {
        $categories = Config::get('lst.categories');
        $cat_ids = explode(',', $categories['229']['children']);
        $case_cats = [];
        foreach ($cat_ids as $cat_id) {
            if (isset($categories[$cat_id])) {
                $case_cats[$cat_id] = $categories[$cat_id]['name'];
            }
        }
        return $case_cats;
    }

    public static function workScope()
    {
        $categories = Config::get('lst.categories');
        $cat_ids = explode(',', $categories['229']['children']);
        $case_cats = [];
        foreach ($cat_ids as $cat_id) {
            if (isset($categories[$cat_id])) {
                $case_cats[] = [
                    'key' => $cat_id,
                    'value' => $categories[$cat_id]['name']
                ];
            }
        }
        return $case_cats;
    }

    public static function getWorkScopeName($key)
    {
        $work_scopes = self::workScope();
        foreach ($work_scopes as $work_scope) {
            if ($work_scope['key'] == $key) {
                return $work_scope['value'];
            }
        }
        return null;
    }

    public static function getActualWorkScopes($workScopeStr)
    {
        $workScopeArr = [];
        $workScopeList = self::workScope();
        $originalWorkScopeArr = explode(",", $workScopeStr);
        foreach ($originalWorkScopeArr as $workScope) {
            if(empty($workScope)) continue;
            $workScopeArr[] = array(
                'key' => $workScope,
                'value' => self::getWorkScopeName($workScope)
            );
        }
        return $workScopeArr;
    }

    public static function get_lawyer_work_scope($work_scope)
    {
        $work_scopes = '';
        if ($work_scope) {
            $work_scope_ids = explode(',', $work_scope);
            foreach ($work_scope_ids as $work_scope_id) {
                $work_scopes .= self::getWorkScopeName($work_scope_id) . ' ';
            }
        }
        return $work_scopes;
    }

    public static function get_client_city_info_by_taobao_service()
    {
        $ctx = stream_context_create(array(
            'http' => array(
                'timeout' => 1,
                'method' => "GET"
            )
        ));
        
        $client_ip = Request::getClientIp();
        if ($client_ip == '127.0.0.1') {
            $client_ip = '183.38.69.219';
        }
        
        $url = sprintf('http://ip.taobao.com/service/getIpInfo.php?ip=%s', urlencode($client_ip));
        
        try {
            $data = file_get_contents($url);
            if ($data) {
                $data = json_decode($data, TRUE);
                $area_data = Config::get('area');
                $city_id = empty($data['data']['city_id']) ? 0 : intval($data['data']['city_id']);
                $region_id = empty($data['data']['region_id']) ? 0 : intval($data['data']['region_id']);
                
                if (isset($area_data[$city_id])) {
                    return array(
                        'city_id' => $city_id,
                        'region_id' => $region_id
                    );
                }
            }
            
            return NULL;
        } catch (Exception $e) {
            return NULL;
        }
    }

    public static function generateRandomNumbers($length)
    {
        $ret = '';
        for ($i = 0; $i < $length; $i ++) {
            $ret .= rand(0, 9);
        }
        return $ret;
    }

    public static function generateRandomString($length)
    {
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $ret = '';
        for ($i = 0; $i < $length; $i ++) {
            $n = rand(0, strlen($s) - 1);
            $ret .= $s[$n];
        }
        return $ret;
    }

    public static function getHashName($key)
    {
        $filename = $_FILES[$key]['name'];
        $_tmp = explode('.', $filename);
        $ext = end($_tmp);
        $hashname = sha1(time() . self::generateRandomString(4)) . '.' . $ext;
        return $hashname;
    }

    /**
     * 根据经纬度获取地理信息
     * 
     * @param float $lat
     *            纬度
     * @param float $lng
     *            经度
     * @return array
     */
    public static function get_client_city_info_by_latlng($lat, $lng)
    {
        $ctx = stream_context_create(array(
            'http' => array(
                'timeout' => 1,
                'method' => "GET",
                'header' => "Origin: m.wdlst.com\r\nReferer: http://m.wdlst.com\r\n"
            )
        ));
        $url = sprintf("http://apis.map.qq.com/ws/geocoder/v1?location=%f,%f&key=%s&coord_type=1&get_poi=0", $lat, $lng, Config::get('interface.qqmap.key'));
        try {
            $data = file_get_contents($url, 0, $ctx);
            $rs = json_decode($data, 1);
            if ($rs['status'] == 0) {
                $district_id = $rs['result']['ad_info']['adcode'];
                $province_id = substr($district_id, 0, 2) . '0000';
                $city_id = substr($district_id, 0, 4) . '00';
                $district_name = AreaHelper::areaCodeToName($district_id);
                $province_name = AreaHelper::areaCodeToName($province_id);
                $city_name = AreaHelper::areaCodeToName($city_id);
                return compact('district_id', 'city_id', 'province_id', 'district_name', 'city_name', 'province_name');
            }
            return null;
        } catch (Exception $exp) {}
        return null;
    }

    public static function getPublishedDates()
    {
        return array(
            '1day' => '今天',
            '3days' => '3天内',
            '1week' => '一周之内',
            '2weeks' => '半月内',
            '1month' => '一个月内'
        );
    }

    public static function getCities()
    {
        return array(
            '110000' => '北京市',
            '310000' => '上海市',
            '440300' => '深圳市',
            '440100' => '广州市'
        );
    }

    public static function getImage($img, $default=null)
    {
        if ($default) {
            $default = Config::get('app.url') . "/" . $default;
        }
        
        $upload_root = Config::get('app.upload_root');
        $uploadfile = $upload_root . $img;
//		Log::info('-----------uploadfile='.$uploadfile);
        if (file_exists($uploadfile) && !($img==null)) {
            $image = route('file.show_image') . "?path=" . $img;
        } else {
            $image = $default;
        }
        
        return $image;
    }

    public static function getFile($path)
    {
        return route('file.download_file') . "?path=" . $path;
    }

    public static function getPracticePeriods()
    {
        return [
            [
                'key' => '1to3',
                'value' => '1-3年'
            ],
            [
                'key' => '3to5',
                'value' => '3-5年'
            ],
            [
                'key' => '5to10',
                'value' => '5-10年'
            ],
            [
                'key' => '10',
                'value' => '10年以上'
            ]
        ];
    }

    public static function getPostStatusStr($status)
    {
        $statusStr = "";
        switch ($status) {
            case 'new':
                $statusStr = '待受理';
                break;
            case 'replied':
                $statusStr = '待确认';
                break;
            case 'wait_for_evaluation':
                $statusStr = '待评价';
                break;
            case 'complete':
                $statusStr = '已完成';
                break;
            case 'cancelled':
                $statusStr = '已取消';
                break;
            case 'refused':
                $statusStr = '已拒绝';
                break;
            case 'wait_pay':
                $statusStr = '待付款';
                break;
        }
        return $statusStr;
    }

    public static function getTypeStr($postType)
    {
        $postTypeStr = "";
        switch ($postType) {
            case Post::TYPE_QUESTION:
                $postTypeStr = '免费咨询';
                break;
            case Post::TYPE_GROUP_POST:
                $postTypeStr = '微博动态';
                break;
            case Post::TYPE_DOC_AUDIT:
                $postTypeStr = '法律文书';
                break;
            case Post::TYPE_LAWSUIT:
                $postTypeStr = '案例';
                break;
            case Post::TYPE_PAY_TEXT:
                $postTypeStr = '图文咨询';
                break;
            case Post::TYPE_PAY_PHONE:
                $postTypeStr = '电话咨询';
                break;
            case Post::TYPE_PAY_COMPANY:
                $postTypeStr = '法律顾问';
                break;
        }
        return $postTypeStr;
    }

    public static function getPracticePeriodStr($practicePeriod)
    {
        $practicePeriodStrs = self::getPracticePeriods();
        foreach ($practicePeriodStrs as $data) {
            if ($data['key'] == $practicePeriod) {
                return $data['value'];
            }
        }
        return '';
    }

    public static function parsePracticePeriods($practice_period)
    {
        $return = array();
        switch ($practice_period) {
            case '1to3':
                $return['min'] = 1;
                $return['max'] = 3;
                break;
            case '3to5':
                $return['min'] = 3;
                $return['max'] = 5;
                break;
            case '5to10':
                $return['min'] = 5;
                $return['max'] = 10;
                break;
            case '10':
                $return['min'] = 10;
                break;
        }
        return $return;
    }

    public static function replaceSensitiveWord($str)
    {
        $arr = file("./sensitive_word.txt"); // 敏感词典
        $arr1 = array();
        foreach ($arr as $k => $v) {
            $arr1["num" . $k] = trim($v);
        }
        $content = str_replace($arr1, "*", $str);
        return $content;
    }

    /**
     * 标准化时间差,传入一个时间,与当前时间对比
     * @param $time
     * @return string|void
     */
    public static function differenceFormat($time)
    {
        $now_year	= (int)date('Y');
        $carbon 	= \Carbon\Carbon::parse($time);
        $minute 	= $carbon->diffInMinutes();
        $year 		= $carbon->year;
        if ($now_year > $year) {
            return $carbon->format('Y年m月d日');
        } elseif ($minute < 2) {
            return '刚刚';
        } elseif ($minute < 60) {
            return $minute . '分钟前';
        } elseif ($minute < (60 * 24)) {
            $hours = $carbon->diffInHours();

            return $hours . '小时前';
        } elseif ($minute < (60 * 192)) {
            $day = $carbon->diffInDays();

            return $day . '天前';
        } elseif ($minute > (60 * 192)) {
            $date = $carbon->format('m月d日');

            return $date;
        }
    }
}
